package com.swn.common.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2015-2-10.
 */
public class FileUploadUtil {
	public static final List<String> ALLOW_TYPES = Arrays.asList("image/jpg",
			"image/jpeg", "image/png", "image/gif");

	// 文件重命名
	public static String rename(String fileName) {
		int i = fileName.lastIndexOf(".");
		String str = fileName.substring(i);
		return new Date().getTime() + "" + new Random().nextInt(99999999) + str;
	}

	/**
     * 获取文件扩展名
     *
     * @return string
     */
    public static String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    
	// 校验文件类型是否是被允许的
	public static boolean allowUpload(String postfix) {
		return ALLOW_TYPES.contains(postfix);
	}

	/**
	 * 将上传的文件从临时文件目录下转存到指定的文件下
	 * 
	 * @param src
	 * @param dst
	 */
	public static void copy(InputStream in, OutputStream out) {
		try {
			/*InputStream in = null;
			OutputStream out = null;*/
			try {
				/*in = new BufferedInputStream(new FileInputStream(src), 1024);
				out = new BufferedOutputStream(new FileOutputStream(dst), 1024);*/
				byte[] buffer = new byte[1024];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
